package com.itljm.cxrMarket.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itljm.cxrMarket.entity.OrderItems;
import com.itljm.cxrMarket.entity.Orders;
import com.itljm.cxrMarket.entity.Products;
import com.itljm.cxrMarket.entity.dto.OrderItemProductsDTO;
import com.itljm.cxrMarket.entity.dto.OrderStatusCountDTO;
import com.itljm.cxrMarket.mapper.OrderItemsMapper;
import com.itljm.cxrMarket.mapper.ProductsMapper;
import com.itljm.cxrMarket.mapper.ShoppingCartMapper;
import com.itljm.cxrMarket.service.OrdersService;
import com.itljm.cxrMarket.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService{
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderItemsMapper orderItemsMapper;
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Override
    public String insertOrder(Orders order, List<OrderItems> orderItems) {
        // 创建订单
        int i = ordersMapper.insertOrder(order);
        int j = 0;
        int k = 0;
        for (OrderItems orderItem : orderItems) {
            orderItem.setOrderId(order.getOrderId());
            // 创建订单项
            j = orderItemsMapper.insertOrderItem(orderItem);
            // 扣减库存
            int rowsAffected = productsMapper.reduceStockQuantity(orderItem.getProductId(), orderItem.getQuantity());
            if (rowsAffected == 0) {
                return "111"; // 库存不足
            }
            // 清空购物车
            k = shoppingCartMapper.deleteCartItems(order.getUserId(), orderItem.getProductId());
        }
        if (i == 0 || j == 0 ) {
            return "222"; // 创建失败
        }
        return "000"; // 成功
    }

    @Override
    public boolean deleteOrderById(Integer orderId) {
        return ordersMapper.deleteById(orderId)>0;
    }

    @Override
    public Orders selectOrderById(Integer orderId) {
        return ordersMapper.selectOrderById(orderId);
    }

    @Override
    public boolean updateOrderStatus(Integer orderId, Integer status, Date updateTime) {
        return ordersMapper.updateOrderStatus(orderId, status, updateTime)>0;
    }

    @Override
    public List<Orders> selectAllOrdersPage(Page<Orders> page, Wrapper<Orders> entityWrapper) {
        return ordersMapper.selectAllOrdersPage(page, entityWrapper);
    }

    @Override
    public List<Orders> selectAllOrderByUserId(Page<Orders> page, Wrapper<Orders> entityWrapper, Long userId) {
        return ordersMapper.selectOrdersByUserId(page, entityWrapper, userId);
    }

    @Override
    public OrderStatusCountDTO countOrderStatusByUserId(Long userId) {
        return ordersMapper.countOrderStatusByUserId(userId);
    }

    @Override
    public List<OrderItemProductsDTO> selectOrders(Page<Orders> page,Integer status, Long userId) {
        // 1. 查询订单主表
        List<Orders> orders = ordersMapper.selectOrdersByUserIdAndStatus(page, userId, status);
        if (orders.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 获取所有订单ID
        List<Integer> orderIds = orders.stream()
                .map(Orders::getOrderId)
                .collect(Collectors.toList());

        // 3. 批量查询订单项（包含商品信息）
        List<OrderItems> allOrderItems = orderItemsMapper.selectWithProductsByOrderIds(orderIds);

        // 4. 按订单ID分组
        Map<Integer, List<OrderItems>> orderItemsMap = allOrderItems.stream()
                .collect(Collectors.groupingBy(OrderItems::getOrderId));

        // 5. 构建最终DTO
        return orders.stream()
                .map(order -> {
                    OrderItemProductsDTO dto = new OrderItemProductsDTO();
                    dto.setOrderId(order.getOrderId());
                    dto.setOrderTime(order.getOrderTime());
                    dto.setTotalPrice(order.getTotalAmount());
                    dto.setStatus(order.getStatus());
                    dto.setPaymentMethod(order.getPaymentMethod());
                    dto.setGoodsList(orderItemsMap.getOrDefault(order.getOrderId(), Collections.emptyList()));
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public boolean isBuy(Long userId, Integer productId) {
        int buy = ordersMapper.isBuy(userId, productId);
        return buy > 0;
    }

}




